package mz.matafe.bolao

import org.codehaus.groovy.grails.plugins.springsecurity.Secured
import mz.matafe.bolao.User
import mz.matafe.bolao.Role
import grails.converters.JSON

/**
 * User Controller.
 *
 * <p>Handle the users
 *
 * @since 0.0.1
 * @author <a href="mailto:matafe@gmail.com">Maurício T. Ferraz</a>
 */
class UserController extends BolaoController{

    def passwordEncoder

    // the delete, save and update actions only accept POST requests
    static Map allowedMethods = [delete: 'POST', save: 'POST', update: 'POST']

    def index = {
        redirect action: list, params: params
    }

    @Secured(['ROLE_ADMIN'])
    def list = {
        params.max = Math.min(params.max ? params.int('max') : 10, 100)
        [users: User.list(params)]
    }

    @Secured(['ROLE_USER'])
    def show = {
        def user = User.get(params.id)
        if (!user) {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'user.label', default: 'User'), params.id])}"
            redirect uri: '/'
            return
        }

        if (!ifAnyGranted('ROLE_ADMIN') && user.username != getUser().username) {
            flash.message = message(code:"user.not.equals.loggedUser", args:["${params.id}"])
            redirect uri: '/'
            return
        }
        [user: user]
    }

    @Secured(['ROLE_ADMIN'])
    def delete = {
        def user = User.get(params.id)
        if (user) {
            def authPrincipal = authenticateService.principal()
            if (!(authPrincipal instanceof String) && authPrincipal.username == user.username) {
                flash.message = message(code:"user.cannot.auto.delete")
                redirect(action:show,id:user.username)
                return
            }
            else {
                try {
                    //first, delete this person from USER_ROLES table.
                    Role.findAll().each { it.removeFromUsers(user) }
                    user.delete(flush:true)
                    flash.message = "${message(code: 'default.deleted.message', args: [message(code: 'user.label', default: 'User'), user.username])}"
                    redirect(action:list)
                }
                catch(org.springframework.dao.DataIntegrityViolationException e) {
                    flash.message = message(code:"user.cannot.be.deleted", args:["${user.username}"])
                    redirect(action:show,id:params.id)
                }
            }
        }
        else {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'user.label', default: 'User'), params.id])}"
            redirect(action:list)
        }
    }

    @Secured(['ROLE_ADMIN'])
    def edit = {
        def user = User.get(params.id)
        if (!user) {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'user.label', default: 'User'), params.id])}"
            redirect action: list
            return
        }
        return buildUserModel(user)
    }

    /** User update action. */
    @Secured(['ROLE_ADMIN'])
    def update = {
        def user = User.get(params.id)
        if (!user) {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'user.label', default: 'User'), params.id])}"
            redirect action: edit, id: params.id
            return
        }
        long version = params.version.toLong()
        if (user.version > version) {
            user.errors.rejectValue("version", "default.optimistic.locking.failure", [message(code: 'user.label', default: 'User')] as Object[], "Another user has updated this User while you were editing")
            render view: 'edit', model: buildUserModel(user)
            return
        }
        def oldPassword = user.password
        def newPassword = params.password
        user.properties = params
        if (!newPassword.equals(oldPassword)) {
            user.password = passwordEncoder.encodePassword(newPassword, null)
        }
        if (!user.hasErrors() && user.save(flush: true)) {
            Role.findAll().each { it.removeFromUsers(user) }
            addRoles(user)
            flash.message = "${message(code: 'default.updated.message', args: [message(code: 'user.label', default: 'User'), user.username])}"
            redirect action: show, id: user.id
        }
        else {
            render view: 'edit', model: buildUserModel(user)
        }
    }

    @Secured(['ROLE_ADMIN'])
    def create = {
        [user: new User(params), roles: Role.list()]
    }

    /** User save action.  */
    @Secured(['ROLE_ADMIN'])
    def save = {
        def user = new User(params)
        if (user.validate()) {
            user.password = passwordEncoder.encodePassword(params.password, null)
            addRoles(user)
            if (user.save()){
                flash.message = "${message(code: 'default.created.message', args: [message(code: 'user.label', default: 'User'), user.username])}"
                redirect action: show, id: user.id
            }
        }
        else {
            user.password = null
            render view: 'create', model: [roles: Role.list(), user: user]
        }
    }

    private void addRoles(user) {
        //add default role user.
        Role.findByCode('ROLE_USER').addToUsers(user)
        for (String key in params.keySet()) {
            if (key.contains('ROLE') && 'on' == params.get(key)) {
                Role.findByCode(key).addToUsers(user)
            }
        }
    }

    private Map buildUserModel(user) {
        List roles = Role.list()
        roles.sort { r1, r2 ->
            r1.code <=> r2.code
        }
        Set userRoleNames = []
        for (role in user.roles) {
            userRoleNames << role.code
        }
        LinkedHashMap<Role, Boolean> roleMap = [:]
        for (role in roles) {
            roleMap[(role)] = userRoleNames.contains(role.code)
        }
        return [user: user, roleMap: roleMap]
    }

    @Secured(['ROLE_USER'])
    def ranking = {
        render 'Lista dos User'
    }

}
